/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.saber.certificacao.ejbs.stateless;

import br.com.saber.certificacao.ejbs.stateless.interfaces.TutorialBeanLocal;
import br.com.saber.certificacao.modelos.Tutorial;
import br.com.saber.certificacao.modelos.validadores.TutorialValidador;
import br.com.saber.certificacao.modelos.validadores.exceptions.generica.ValidacaoExcecao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Guilherme
 */
@Stateless
public class TutorialBean implements TutorialBeanLocal {

    @PersistenceContext(name = "jdbc/saber")
    private EntityManager manager;
    
    @Override
    public void salvarTutorial(Tutorial tutorial) throws ValidacaoExcecao {
        new TutorialValidador().validar(tutorial, this, null);
        if(tutorial.getId() == null){
            manager.persist(tutorial);
        }else{
            manager.merge(tutorial);
        }
        manager.flush();
    }

    @Override
    public List<Tutorial> buscarTutorialPorIndicePaginado(int posicao, int maxResult, String indice){
        Query q = manager.createNamedQuery("TutorialBean.buscarTutorialPorIndicePaginado");
        if(indice == null){
            indice = "";
        }
        q.setParameter("indice", "%" + indice + "%");
        q.setFirstResult(posicao);
        q.setMaxResults(maxResult);
        return q.getResultList();
    }
    
    @Override
    public Integer buscarQtdadeTutorialPorIndicePaginado(String indice){
        Query q = manager.createNamedQuery("TutorialBean.buscarQtdadeTutorialPorIndicePaginado");
        if(indice == null){
            indice = "";
        }
        q.setParameter("indice", "%" + indice + "%");
        Long toReturn = (Long) q.getSingleResult();
        return toReturn.intValue();
    }
}
